<?php

/**
 * Celebrio nette-bootstrap file.
 */

use Nette\Debug;
use Nette\Environment;
use Nette\Config\Config;
use Nette\Application\Route;
use Nette\Application\SimpleRouter;
use \Microsoft_WindowsAzure_SessionHandler;
use Celebrio\Core\ModuleLoader;
use Celebrio\WindowsAzure\AzureStorage\AzureStorageTable;
use Celebrio\Diagnostics\Timer;
use Celebrio\Diagnostics\TimerLevel;

// Step 1: Load Nette Framework
// this allows load Nette Framework classes automatically so that
// you don't have to litter your code with 'require' statements
require LIBS_DIR . '/Nette/loader.php';

if (extension_loaded("azure")) {
    define("AZURE", true);
} else {
    define("AZURE", false);
}

// sets a tempDir to TempStorage for Windows Azure using local azure storage
if (AZURE) {
    $azureTempDir = azure_getlocalresourcepath("TempStorage");
    Environment::setVariable("tempDir", substr($azureTempDir, 0, -1));
}
// load configuration from config.ini file
Environment::loadConfig();


// TODO: this type of loging is not usable for distributed environment in cloud
// sets a logDir to LogStorage for Windows Azure using local azure storage
if (AZURE) {
    $azureLogDir = azure_getlocalresourcepath("LogStorage");
    Environment::setVariable("logDir", substr($azureLogDir, 0, -1));
}

if (AZURE)
    ini_set('error_log', azure_getlocalresourcepath("ErrorStorage") . 'error_log.txt');

$emailHeaders = array(
    'From' => 'error@celebriosoftware.com',
    'To' => 'feedback@celebriosoftware.com',
    'Subject' => 'Error',
    'Body' => '%date% - %message%. Pro více informací shlédněte error log.',
);

Timer::start($_SERVER["REQUEST_URI"],TimerLevel::REQUEST);

$application = Environment::getApplication();


// ------------------------------------------
// Set up DEBUG for development or production
// ------------------------------------------

define("PRODUCTION", false);
//define("PRODUCTION", true);

if (PRODUCTION) {
    define("CSS", "css");
    Debug::enable(Debug::PRODUCTION, Environment::expand('%logDir%/php_error.log'));
    Debug::$strictMode = false;
    $application->catchExceptions = true;
    $application->errorPresenter = 'Webtop:Error';
} else {
    define("CSS", "less");
    Debug::enable();
    Debug::$strictMode = true;
    $application->catchExceptions = false;
}

// logger initialization (our settings)
\Celebrio\Logging\Logger::initialize();

//$log = Logger::getRootLogger();
//$log->debug(array(1, 2, "zdar", array(10, "x")));
//$log->warn(array(1, 2, "zdar", array(10, "x")));
//$log->fatal(array(1, 2, "zdar", array(10, "x")), new InvalidStateException("ahoj", 10, new \Exception("exc zdar")));

// demo logging - shorthand is preferred
//\Celebrio\Logging\Logger::debug($_SERVER, null, );
//\Celebrio\Logging\Logger::debug("Received request " . $_SERVER["REQUEST_URI"]);
//\Celebrio\Logging\Logger::getLogger("errors")->error("test error - nothing actually happened", new \Exception("testing exception"));

if (AZURE) {
    \Celebrio\Logging\AzureLogHandling::initialize();
    Debug::$onFatalError[] = array('\Celebrio\Logging\AzureLogHandling', "azureStorageLogger"); //pridaj na koniec pola <-- WHAT THE FUCK IS THIS?
}


// ------------------------------------------
// Session storage management
// ------------------------------------------

if (AZURE) {
    // stores session in azure storage tables using php_azure.dll, php azure SDK and configurations in ServiceConfiguration.csdef
    $sessionHandler = new Microsoft_WindowsAzure_SessionHandler(AzureStorageTable::connection(), 'sessionstable');
    $sessionHandler->register();
} else {
    // stores sessions in temp directory
    ini_set('session.save_path', Environment::expand("%tempDir%"));
}


// watching performance on Windows Azure
//if(extension_loaded("azure")) DiagnosticsManagement::addPerformanceCounter('\Processor(*)\% Processor Time');
// Step 3: Configure application
// 3a) get and setup a front controller


Route::addStyle("#kernel");
Route::setStyleProperty("#kernel", Route::FILTER_TABLE, array(
    'sign-in' => 'SignIn',
    'overview' => 'Overview',
    'sign-out' => 'SignOut',

    'php-logs' => 'Logs:Php:Display',
    'php-logs-detail' => 'Logs:Php:Detail',
    'acl-logs' => 'Logs:Acl:Display',
	'performance-logs' => 'Logs:Performance:Display',
	'logger' => 'Logs:Logger:Display',
    'php-logs-process' => 'Logs:Php:Process',
    'logs' => 'Logs:Overview',

    'modules' => 'Modules:ModulesManagement',
    'console' => 'Modules:Console',
    'terminal' => 'Modules:Terminal',
    'google-api' => 'Modules:GoogleApi',

    'acl' => 'Acl:Overview',
    'permissions' => 'Acl:Permissions',
    'privileges' => 'Acl:Privileges',
    'resources' => 'Acl:Resources',

    'user-management' => 'Users:Overview',
    'users' => 'Users:Users',
    'roles' => 'Users:Roles',

    'app-management' => 'Applications:Management'
));

// webtop translation table. it's not necessary since there aren't nested modules
//Route::addStyle("#webtop");
//Route::setStyleProperty("#webtop", Route::FILTER_TABLE, array(
//     'default' => 'Default',
//     'sign' => 'Sign',
//));

Route::addStyle("#applications");
Route::setStyleProperty("#applications", Route::FILTER_TABLE, array(

    'settings' => 'Settings:Default',
    'preferences' => 'Settings:Default',
	'settings-personal' => 'Settings:Personal',
	'settings-appearence' => 'Settings:Appearence',
	'settings-applications' => 'Settings:Applications',

    'weather' => 'Weather:Weather',
    
    'internet' => 'Internet:Default',

    'mail' => 'Mail:Default',
    'mail-compose' => 'Mail:Compose',
    'mail-settings' => 'Mail:Settings',

    'talker' => 'Talker:Default',

    'news' => 'News:Default',

    'chat' => 'Chat:Default',
    'chat-thread' => 'Chat:Thread',

    //'board' => 'Board:Mini',
    //'board-thread' => 'Board:Thread',

    'gallery' => 'Gallery:Default',
    
    'games' => 'Game:Default',
    
    'books' => 'Books:Default',
    
    'people' => 'People:Default',

    'television' => 'TV:Default',
    'application' => 'Application:Application',

    'feedback' => 'Feedback:Default',

    'registration' => 'Registration:Default',

	'wiki' => 'Wiki:Default'
));

// Step 4: Setup application router
$router = $application->getRouter();

$router[] = new Route('kernel/<presenter #kernel>/<action>[/<paginator-page \d+>][/<fullName>]', array(
    'module' => 'Kernel',
    'presenter' => 'Overview',
    'action' => 'default',
));

$router[] = new Route('api/<presenter>/<action>[/<id \d+>]', array(
    'module' => 'Api',
    'presenter' => 'Rest',
    'action' => 'default',
    'id' => null,
));

$router[] = new Route('app/<presenter #applications>/<action>', array(
    'module' => 'Applications',
    'action' => 'default',
));

$router[] = new Route('facebook-app/<action>/', array(
    'module' => 'Web',
    'presenter' => 'FacebookApp',
    'action' => 'default',
));

$router[] = new Route('video/<action>/', array(
    'module' => 'Web',
    'presenter' => 'Video',
    'action' => 'default',
));


$router[] = new Route('<presenter>/<action>/', array(
    'module' => 'Webtop',
    'presenter' => 'Default',
    'action' => 'default',
));

if (!Environment::getSession()->isStarted()) {
    Environment::getSession()->start();
}

// This part is for "smart" latte forms
\Nette\Templates\FormMacros::register();

// the module loader loads installed modules (runs init methods)
Timer::start("Module loader",TimerLevel::OVERVIEW);
$moduleLoader = new ModuleLoader();
$moduleLoader->loadInstalled();
Timer::stop("Module loader");

// Step 5: Run the application!
Timer::start("Application run",TimerLevel::OVERVIEW);
$application->run();
Timer::stop("Application run");

Timer::stop($_SERVER["REQUEST_URI"]);